package cn.hg.solon.youcan.framework.web.filter;

import java.util.Date;

import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.core.handle.Context;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hg.solon.youcan.common.constant.OnlineConstants;

/**
 * @author 胡高
 */
public class UserOnlineSyncHandler {

    public static void handle(Context ctx) throws Throwable{
        // 如果未登录，则跳过
        if (!StpUtil.isLogin()) {
            return;
        }

        SaSession session = StpUtil.getTokenSession();
        SaTokenInfo token = StpUtil.getTokenInfo();

        // 更新用户最后活动时间
        Date lastSyncTimestamp = (Date) session.get(OnlineConstants.LAST_SYNC_DB_TIMESTAMP);
        Date now = DateUtil.now();

        StpUtil.updateLastActivityToNow();
        session.set(OnlineConstants.EXPIRATION_DATETIME, DateUtil.offsetSecond(now,
            StpUtil.getTokenActivityTimeout() > Integer.MAX_VALUE ? Integer.MAX_VALUE : Convert.toInt(StpUtil.getTokenActivityTimeout())));

        if (ObjUtil.isNull(lastSyncTimestamp) || (now.getTime() - lastSyncTimestamp.getTime()) > OnlineConstants.SYNC_PERIOD) {
            session.set(OnlineConstants.LAST_SYNC_DB_TIMESTAMP, now);
            EventBus.pushAsync(token);
        }
    }
}
